import { createStore } from 'vuex';
import { GetInfoApi } from '../request/api';
interface MenuObj {
  parentId: number;
  id: number;
  children?: MenuObj[];
  title: string;
  name: string;
}
interface State {
  menus: MenuObj[];
  userName: string;
}
interface NewMenu {
  [key: string]: MenuObj;
}
const store = createStore<State>({
  state() {
    return {
      // 首页菜单
      menus: [],
      //   登录用户名
      userName: '',
    };
  },
  getters: {
    //   对state里面的数据进行处理，处理成想要的样子
    // [{},{}]=>[{title:'',children:[{},{}]},{...}]
    getNewMenus(state) {
      const menus = state.menus;
      //   一级菜单数组
      const FirstMenu: NewMenu = {};
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].parentId == 0) {
          // 一级菜单 FirstMenu[key]=value
          // 如果顺序乱了，二级菜单在前，会导致一级菜单是空对象，
          FirstMenu[menus[i].id] = { ...menus[i], ...FirstMenu[menus[i].id] };
        } else {
          // 二级菜单
          const SecondMenu = menus[i];
          //  FirstMenu[SecondMenu.parentId]有可能是undefined，这里给个默认值
          FirstMenu[SecondMenu.parentId] = FirstMenu[SecondMenu.parentId] || {};
          FirstMenu[SecondMenu.parentId].children =
            FirstMenu[SecondMenu.parentId].children || [];
          //   添加二级菜单到对应的一级菜单对象上的children
          FirstMenu[SecondMenu.parentId].children?.push(SecondMenu);
        }
      }
      return FirstMenu;
    },
    permissionMenus(state) {
      return state.menus.map((item) => item.name);
    },
  },
  mutations: {
    //   更新state的首页菜单数组
    updataMenus(state, payload) {
      state.menus = payload;
    },
    // 更新用户名
    updataUserName(state, payload) {
      state.userName = payload;
    },
  },
  actions: {
    // getInfo({ commit }) {
    //   return new Promise((resolve, reject) => {
    //     GetInfoApi().then((res) => {
    //       if (res.code == 200) {
    //         commit('updataMenus', res.data.menus);
    //         commit('updataUserName', res.data.username);
    //         resolve(res.data);
    //       } else {
    //         reject(res);
    //       }
    //     });
    //   });
    // },
  },
});
export default store;
